<script setup lang='ts'>
import { useRouter } from 'vue-router';
import{ getBirdsListService } from '@/api/birds'
import { addHistoryService} from '@/api/history'
import { useUserStore }  from '@/stores/user'

const userStore = useUserStore();

const router = useRouter();

interface History {
    UID: string;
    action: string;
    result: string;
    birdUrl: string;
}

//定义一个对象来存储历史记录数据
const historyInfo = ref<History>();

//调用后端接口添加历史记录
const addHistory = async (historyInfo: History) => {

    let result = await addHistoryService(historyInfo);

    if(result.code == 200){
        ElMessage.success(result.msg ? result.msg : '添加历史记录成功');
    }else{
        ElMessage.error(result.msg ? result.msg : '添加历史记录失败');
    }

};

const toBirdDetail = (birdId: number) => {

     //添加历史记录
     if (userStore.user.uid) { // 确保 uid 不为 null
        historyInfo.value = {
            UID: userStore.user.uid,
            action: '浏览鸟类',
            result: '成功',
            birdUrl: '/home/birdDetail/' + birdId
        };
        // console.log(historyInfo.value);
        addHistory(historyInfo.value); // 使用 await 等待异步操作完成
    } else {
        console.error("User ID is null");
    }

    router.push('/home/birdDetail/' + birdId);

};

interface Bird {
    id: number;
    createdAt: string;
    updatedAt: string;
    morphologyAndFeatures: string;
    name: string;
    habits: string;
    species: string;
    imageUrl: string;
    soundUrl: string;
    description: string;
    growthAndDistribution: string;
}

//定义一个对象来存储鸟类列表数据
const birdsList = ref<Bird[]>([]);

//调用后端接口获取鸟类列表
const getBirdsList = async () => {
    
    let result = await getBirdsListService();

    //TODO 感觉之前好多地方都忘记加判断是否成功了，记得检查一下，失败要有提示
    //如果成功则将数据赋值给birdsList，失败则弹出提示
    if(result.code == 200){
        birdsList.value = result.data;
    }else{
        ElMessage.error(result.msg ? result.msg : '获取鸟类列表失败');
    }

};
getBirdsList();

</script>

<template>
    <div class="container">
        
        <!-- 使用 v-for 循环遍历鸟类列表数据，并在每个卡片中展示对应的鸟类信息 -->
        <el-card v-for="bird in birdsList"
        style="width: 300px; height: 300px; " 
        @click="toBirdDetail(bird.id)"> 
            <template #header>{{ bird.name }}</template>
            <div style="width: 260px; height: 200px;">
                <img loading="lazy" :src="bird.imageUrl"
            style="width: 100%; height: 100%; object-fit: contain;" />
            </div>
        </el-card>
        
    </div>
</template>

<style scoped>
.container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    /* overflow: auto; */
}
.el-card{
    margin: 10px;
    cursor: pointer;
}
</style>